//
//  TaurusDbHelper.swift
//  SwiftLibrary
//
//  Created by wumin on 15/12/31.
//  Copyright © 2015年 taurusxi. All rights reserved.
//

import Foundation

let DB_NAME = "TaurusDB"
let SQLITE_NAME = "taurus.sqlite"

/** SQLite五种数据类型 */
let SQLTEXT = "TEXT"
let SQLINTEGER = "INTEGER"
let SQLREAL = "REAL" // 浮点数
let SQLBLOB = "BLOB"
let SQLNULL = "NULL"
let PRIMARY_KEY = "primary key "

//let primaryId   = "pk"

let VERSION_TABBLE_NAME = "version_table"
let SELECT_VERSION_SQL = "select t.version from \(VERSION_TABBLE_NAME) t where t.tableName =  "
let INSERT_VERSION_SQL = "insert into \(VERSION_TABBLE_NAME) values "

let UNDIFINE_INTERGER_VALUE = -121

let DB_LOG_FLAG = true

//var createTableIndexDic:[String:Bo ol] = [:]

func registerDBModel(_ clazz: TaurusDBModel.Type) {
  clazz.createTable()
}

func printDBLog( _ closure: @autoclosure () -> (String)) {
  if DB_LOG_FLAG {
    print(closure())
  }
}

func getTableName(_ clazz: TaurusDBModel.Type) -> String {
  return (NSStringFromClass(clazz) as NSString).replacingOccurrences(of: ".", with: "_").uppercased()
}

class TaurusDbHelper {
  static let sharedInstance = TaurusDbHelper()
  
  fileprivate init() { }
  
  lazy var dbQueue: FMDatabaseQueue? = {
    
    let queue = FMDatabaseQueue.init(path: TaurusDbHelper.dbPath())
    queue?.inTransaction {
      db, rollback in
      do {
        try db?.executeUpdate("CREATE TABLE IF NOT EXISTS \(VERSION_TABBLE_NAME) ( tableName TEXT primary key , version INTEGER )", values: nil)
        printDBLog("创建 Version表")
      } catch _ {
      }
    }
    return queue
  }()
  
  static func dbPathWithDirectoryName(_ directoryName: String?) -> String {
    
    var docsDir = (NSSearchPathForDirectoriesInDomains(.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!) as NSString
    let fileManager = FileManager.default
    
    if let dName = directoryName ,(dName as NSString).length > 0 {
      docsDir = docsDir.appendingPathComponent(dName) as NSString
    } else {
      docsDir = docsDir.appendingPathComponent(DB_NAME) as NSString
    }
    
    var isDir: ObjCBool = false

    let exitFlag = fileManager.fileExists(atPath: docsDir as String, isDirectory: &isDir)
    
    if !exitFlag && !isDir.boolValue {
      
      do {
        try fileManager.createDirectory(atPath: docsDir as String, withIntermediateDirectories: true, attributes: nil)
      } catch _ {
      }
    }
    let dbPath = docsDir.appendingPathComponent(SQLITE_NAME)
    printDBLog(dbPath)
    return dbPath
  }
  
  static func dbPath() -> String {
    return dbPathWithDirectoryName(nil)
  }
  
  func changeDBWithDirectoryName(_ directoryName: String) -> Bool {
    if (self.dbQueue != nil) {
      self.dbQueue = nil
    }
    self.dbQueue = FMDatabaseQueue.init(path: TaurusDbHelper.dbPathWithDirectoryName(directoryName))
    
//    var numbClasses = 0;
    
    return true
  }
}
